package com.xiangxiao.rpan.data.producer.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xiangxiao.rpan.data.constant.GlobalConsts;
import com.xiangxiao.rpan.data.consumer.IConsumerAuthorityClient;
import com.xiangxiao.rpan.data.dto.MqttFileUploadDto;
import com.xiangxiao.rpan.data.dto.QueryUsersByTopicDto;
import com.xiangxiao.rpan.data.enums.MessageTypeEnum;
import com.xiangxiao.rpan.data.model.FileUploadAlarm;
import com.xiangxiao.rpan.data.model.FloderUploadAlarm;
import com.xiangxiao.rpan.data.mqtt.MyMqttServer;
import com.xiangxiao.rpan.data.producer.AlarmProduce;
import com.xiangxiao.rpan.data.service.AlarmInfoService;
import com.xiangxiao.rpan.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2024/5/11 15:44
 */
@Component
@Slf4j
public class FileUploadAlarmProduce implements AlarmProduce<FileUploadAlarm> {
  @Autowired
  private AlarmInfoService alarmInfoService;
  @Autowired
  private IConsumerAuthorityClient consumerAuthorityClient;

  public FileUploadAlarmProduce(){
    super();
  }

  @Override
  public MessageTypeEnum getMessageTypeEnum() {
    return MessageTypeEnum.FILEUPLOAD;
  }

  @Override
  public void alarm(FileUploadAlarm m) {
    Integer alarmId = saveAlarm(m);
    if (alarmId == null) {
      log.error("接受告警-保存告警失败，targetId:{}", m.getId());
      return;
    };
    m.setId(alarmId);
    List<String> mqttTopicPrefix = getMqttTopicPrefix(m);
    Set<Integer> sendUserIdList = getSendUserIdList(m);
    System.out.println("发送的用户id列表为:");
    System.out.println(sendUserIdList);
    if (CollectionUtils.isEmpty(sendUserIdList)) {
      log.info("接受告警-无对应的告警发送人,告警信息:{}", JSONObject.toJSONString(m));
    };
    sendUserIdList.forEach(userId -> {
      sendAlarmMq(m, mqttTopicPrefix, userId);
    });
  }

  private void sendAlarmMq(FileUploadAlarm m, List<String> mqttTopicPrefix, Integer userId) {
    mqttTopicPrefix.forEach(topic -> {
      if (!sendMQTTBefore(m)) {
        return;
      }
      sendMQTT(topic + "/" + userId, m);

    });

    sendMqttAfter(m, userId);
  }

  @Override
  public Integer saveAlarm(FileUploadAlarm fileUploadAlarm) {
    Integer id = alarmInfoService.insertFileUploadAlarm(fileUploadAlarm);
    return id;
  }

  @Override
  public boolean sendMQTTBefore(FileUploadAlarm fileUploadAlarm) {
    return true;
  }

  @Override
  public void sendMQTT(String topic, FileUploadAlarm fileUploadAlarm) {
    MyMqttServer.post(topic, JSONObject.toJSONString(coverAlarmToMqttData(fileUploadAlarm)));
  }

  @Override
  public void sendMqttAfter(FileUploadAlarm fileUploadAlarm, Integer userId) {

  }

  @Override
  public Set<Integer> getSendUserIdList(FileUploadAlarm fileUploadAlarm) {
    Set<Integer> userIdSet = new HashSet<>();
//    userIdSet.add(1);
//    userIdSet.add(11);
//    userIdSet.add(14);
    try {
      QueryUsersByTopicDto dto = new QueryUsersByTopicDto();
      dto.setTopic(GlobalConsts.ALARM_PREFIX + fileUploadAlarm.getMessageType().getMqttTopic());
      System.out.println(dto.toString());
      JSONObject resp = consumerAuthorityClient.queryUserIdsByTopic(dto);

      List<Integer> ids = resp.getJSONArray("data").toJavaList(Integer.class);
      userIdSet = new HashSet<Integer>(ids);
      return userIdSet;
    } catch (RuntimeException e) {
      e.printStackTrace();
      return userIdSet;
    }
  }

  @Override
  public List<String> getMqttTopicPrefix(FileUploadAlarm fileUploadAlarm) {
    return Collections.singletonList(fileUploadAlarm.getMessageType().getMqttTopic());
  }

  @Override
  public Object coverAlarmToMqttData(FileUploadAlarm alarm) {
    SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_DATETIME_CN);
    MqttFileUploadDto dto = new MqttFileUploadDto();

    dto.setId(alarm.getId());
    dto.setType(alarm.getType());
    dto.setTime(sdf.format(alarm.getTime()));
    dto.setStatus(alarm.getStatus().getCode());
    dto.setFileId(alarm.getFileId());
    dto.setFileExtension(alarm.getFileExtension());
    dto.setFilePath(alarm.getFilePath());
    dto.setName(alarm.getName());
    if (alarm.getStartTime() != null) {
      dto.setStartTime(sdf.format(alarm.getStartTime()));
    }
    ;
    if (alarm.getFinishTime() != null) {
      dto.setFinishTime(sdf.format(alarm.getFinishTime()));
    }
    ;
    dto.setOperator(alarm.getOperator());
    dto.setSize(alarm.getSize());
    return dto;
  }
}
